<template>
  <div class="order-payment">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>商品入库</h1>
      <div class="breadcrumb">仓库管理 > 商品入库</div>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <div class="search-form">
        <div class="form-item">
          <label>入库单号</label>
          <input v-model="searchForm.grnCode" type="text" placeholder="请输入入库单号" />
        </div>
        <div class="form-item">
          <label>仓库</label>
          <select v-model="searchForm.warehouseId">
            <option value="">全部</option>
            <option v-for="item in warehouses" :key="item.id" :value="item.id">{{ item.whName }}</option>
          </select>
        </div>
        <div class="form-item">
          <label>状态</label>
          <select v-model="searchForm.status">
            <option value="">全部</option>
            <option :value="0">草稿</option>
            <option :value="1">待审核</option>
            <option :value="2">已审核</option>
            <option :value="3">已完成</option>
          </select>
        </div>
        <div class="form-buttons">
          <button class="btn btn-primary" @click="fetchGrnList">查询</button>
          <button class="btn btn-secondary" @click="resetSearch">重置</button>
        </div>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-bar">
      <button class="btn btn-primary" @click="handleCreate">新建入库单</button>
    </div>

    <!-- 入库单列表 -->
    <div class="table-container">
      <table class="data-table">
        <thead>
        <tr>
          <th><input type="checkbox" v-model="selectAll" @change="toggleSelectAll" /></th>
          <th>入库单号</th>
          <th>采购单号</th>
          <th>仓库</th>
          <th>商品数量</th>
          <th>状态</th>
          <th>创建时间</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="item in grnList" :key="item.id">
          <td><input type="checkbox" v-model="item.selected" /></td>
          <td>{{ item.grnCode }}</td>
          <td>{{ item.poId || '-' }}</td>
          <td>{{ getWarehouseName(item.warehouseId) }}</td>
          <td>{{ item.itemCount || 0 }}</td>
          <td>
            <span :class="getStatusClass(item.status)">{{ getStatusText(item.status) }}</span>
          </td>
          <td>{{ formatDate(item.createdAt) }}</td>
          <td>
            <button class="btn btn-small btn-info" @click="handleView(item)">查看</button>
            <button v-if="item.status === 4" class="btn btn-small btn-warning" @click="handleEdit(item)">编辑</button>
            <button v-if="item.status === 0 || item.status === 4" class="btn btn-small btn-primary" @click="handleSubmit(item.id)">提交审核</button>
            <button v-if="item.status === 1" class="btn btn-small btn-success" @click="handleApprove(item)">审核</button>
            <button v-if="item.status === 2" class="btn btn-small btn-primary" @click="handleExecute(item.id)">入库</button>
            <button v-if="item.status === 0" class="btn btn-small btn-danger" @click="handleDelete(item.id)">删除</button>
          </td>
        </tr>
        <tr v-if="grnList.length === 0">
          <td colspan="8" class="text-center">暂无数据</td>
        </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页 -->
    <div class="pagination" v-if="pagination.total > 0">
      <div class="pagination-info">
        共{{ Math.ceil(pagination.total / pagination.size) }}页/{{ pagination.total }}条数据
      </div>
      <div class="pagination-controls">
        <button class="btn btn-page" :disabled="pagination.current === 1" @click="changePage(pagination.current - 1)">上一页</button>
        <button
            v-for="page in visiblePages"
            :key="page"
            class="btn btn-page"
            :class="{ active: page === pagination.current }"
            @click="changePage(page)"
        >
          {{ page }}
        </button>
        <button class="btn btn-page" :disabled="pagination.current === Math.ceil(pagination.total / pagination.size)" @click="changePage(pagination.current + 1)">下一页</button>
      </div>
      <div class="pagination-jump">
        <span>跳至</span>
        <input type="number" v-model="jumpPage" min="1" :max="Math.ceil(pagination.total / pagination.size)" />
        <span>页</span>
        <button class="btn btn-small" @click="jumpToPage">确定</button>
      </div>
    </div>

    <!-- 入库单详情对话框 -->
    <div v-if="detailDialog.visible" class="modal-overlay" @click="detailDialog.visible = false">
      <div class="modal-content" style="width: 80%;" @click.stop>
        <div class="modal-header">
          <h3>入库单详情</h3>
          <button class="modal-close" @click="detailDialog.visible = false">&times;</button>
      </div>
        <div class="modal-body">
        <div class="detail-header">
            <div class="detail-row">
          <div class="detail-item">
                <span class="detail-label">入库单号：</span>
                <span>{{ detailDialog.data.grn?.grnCode || '' }}</span>
          </div>
          <div class="detail-item">
                <span class="detail-label">采购单号：</span>
                <span>{{ detailDialog.data.grn?.poId || '-' }}</span>
              </div>
          </div>
            <div class="detail-row">
          <div class="detail-item">
                <span class="detail-label">仓库：</span>
                <span>{{ getWarehouseName(detailDialog.data.grn?.warehouseId) }}</span>
          </div>
          <div class="detail-item">
                <span class="detail-label">状态：</span>
                <span :class="getStatusClass(detailDialog.data.grn?.status)">
                  {{ getStatusText(detailDialog.data.grn?.status) }}
                </span>
              </div>
          </div>
            <div class="detail-row">
          <div class="detail-item">
                <span class="detail-label">创建时间：</span>
                <span>{{ formatDate(detailDialog.data.grn?.createdAt) }}</span>
              </div>
            </div>
          </div>

          <div class="detail-content">
            <!-- 详情选项卡 -->
            <div class="detail-tabs">
              <div class="tab-header">
                <button 
                  class="tab-btn" 
                  :class="{ active: detailActiveTab === 'items' }" 
                  @click="detailActiveTab = 'items'"
                >
                  入库商品
                </button>
                <button 
                  class="tab-btn" 
                  :class="{ active: detailActiveTab === 'history' }" 
                  @click="detailActiveTab = 'history'"
                >
                  操作历史
                </button>
                <button 
                  class="tab-btn" 
                  :class="{ active: detailActiveTab === 'summary' }" 
                  @click="detailActiveTab = 'summary'"
                >
                  汇总信息
                </button>
              </div>

              <!-- 入库商品明细 -->
              <div v-show="detailActiveTab === 'items'" class="tab-content">
                <table class="data-table">
                  <thead>
                    <tr>
                      <th>商品名称</th>
                      <th>商品编码</th>
                      <th>批次号</th>
                      <th>库位</th>
                      <th>数量</th>
                      <th>单价</th>
                      <th>总金额</th>
                      <th>备注</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="(item, index) in detailDialog.data.items || []" :key="index">
                      <td>{{ item.skuName || getProductName(item.skuId) }}</td>
                      <td>{{ item.skuCode || getSkuCode(item.skuId) }}</td>
                      <td>{{ item.batchNo || '-' }}</td>
                      <td>{{ getLocationName(item.locationId) }}</td>
                      <td>{{ item.qty || item.quantity }}</td>
                      <td>{{ formatCurrency(item.price || item.unitPrice) }}</td>
                      <td>{{ formatCurrency((item.qty || item.quantity) * (item.price || item.unitPrice)) }}</td>
                      <td>{{ item.remark || '-' }}</td>
                    </tr>
                    <tr v-if="(detailDialog.data.items || []).length === 0">
                      <td colspan="8" class="text-center">暂无数据</td>
                    </tr>
                  </tbody>
                </table>
              </div>

              <!-- 操作历史 -->
              <div v-show="detailActiveTab === 'history'" class="tab-content">
                <table class="data-table">
                  <thead>
                    <tr>
                      <th>操作时间</th>
                      <th>操作类型</th>
                      <th>操作人</th>
                      <th>状态变更</th>
                      <th>备注</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="(record, index) in operationHistory" :key="index">
                      <td>{{ formatDate(record.operateTime) }}</td>
                      <td>{{ record.operationType }}</td>
                      <td>{{ record.operator }}</td>
                      <td>{{ record.statusChange }}</td>
                      <td>{{ record.remark || '-' }}</td>
                    </tr>
                    <tr v-if="operationHistory.length === 0">
                      <td colspan="5" class="text-center">暂无操作记录</td>
                    </tr>
                  </tbody>
                </table>
              </div>

              <!-- 汇总信息 -->
              <div v-show="detailActiveTab === 'summary'" class="tab-content">
                <div class="summary-grid">
                  <div class="summary-card">
                    <h4>商品统计</h4>
                    <div class="stat-item">
                      <span class="stat-label">商品种类：</span>
                      <span class="stat-value">{{ (detailDialog.data.items || []).length }}种</span>
                    </div>
                    <div class="stat-item">
                      <span class="stat-label">总数量：</span>
                      <span class="stat-value">{{ getTotalQuantity() }}件</span>
                    </div>
                    <div class="stat-item">
                      <span class="stat-label">总金额：</span>
                      <span class="stat-value">{{ formatCurrency(getTotalAmount()) }}</span>
                    </div>
                  </div>
                  <div class="summary-card">
                    <h4>单据信息</h4>
                    <div class="stat-item">
                      <span class="stat-label">供应商ID：</span>
                      <span class="stat-value">{{ detailDialog.data.grn?.supplierId || '-' }}</span>
                    </div>
                    <div class="stat-item">
                      <span class="stat-label">入库类型：</span>
                      <span class="stat-value">{{ detailDialog.data.grn?.inboundType || '采购入库' }}</span>
                    </div>
                    <div class="stat-item">
                      <span class="stat-label">经办人：</span>
                      <span class="stat-value">{{ detailDialog.data.grn?.handler || '-' }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="detailDialog.visible = false">关闭</button>
        </div>
      </div>
    </div>

    <!-- 新建入库单对话框 -->
    <div v-if="createDialog.visible" class="modal-overlay" @click="createDialog.visible = false">
      <div class="modal-content" style="width: 80%;" @click.stop>
        <div class="modal-header">
          <h3>新建入库单</h3>
          <button class="modal-close" @click="createDialog.visible = false">&times;</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>入库单号</label>
            <input type="text" v-model="createDialog.form.grnCode" placeholder="请输入入库单号" />
          </div>
          <div class="form-group">
            <label>采购单号</label>
            <input type="text" v-model="createDialog.form.poId" placeholder="请输入采购单号" />
          </div>
          <div class="form-group">
            <label>入库仓库</label>
            <select v-model="createDialog.form.warehouseId">
              <option value="">请选择仓库</option>
              <option v-for="item in warehouses" :key="item.id" :value="item.id">{{ item.whName }}</option>
            </select>
          </div>

          <div class="divider">
            <span>入库商品</span>
          </div>
        
          <div class="items-container">
            <table class="data-table">
              <thead>
                <tr>
                  <th>商品名称</th>
                  <th>数量</th>
                  <th>单价</th>
                  <th>备注</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in createDialog.form.items" :key="index">
                  <td>
                    <select v-model="item.skuId" @change="() => handleProductSelect(item.skuId, index)">
                      <option value="">请选择商品</option>
                      <option v-for="prod in products" :key="prod.id" :value="prod.id">{{ prod.productName }}</option>
                    </select>
                  </td>
                  <td>
                    <input type="number" v-model="item.quantity" min="1" placeholder="数量" />
                  </td>
                  <td>
                    <input type="number" v-model="item.unitPrice" step="0.01" min="0" placeholder="单价" />
                  </td>
                  <td>
                    <input type="text" v-model="item.remark" placeholder="备注" />
                  </td>
                  <td>
                    <button v-if="index === 0" class="btn btn-small btn-success" @click="addItemRow">添加</button>
                    <button v-else class="btn btn-small btn-danger" @click="removeItemRow(index)">删除</button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="createDialog.visible = false">取消</button>
          <button class="btn btn-primary" @click="submitGrn" :disabled="createDialog.loading">确认</button>
        </div>
      </div>
    </div>

    <!-- 编辑对话框 -->
    <div v-if="editDialog.visible" class="modal-overlay" @click="editDialog.visible = false">
      <div class="modal-content" style="width: 80%;" @click.stop>
        <div class="modal-header">
          <h3>编辑入库单 - {{ editDialog.data.grn?.grnCode }}</h3>
          <button class="modal-close" @click="editDialog.visible = false">&times;</button>
        </div>
        <div class="modal-body">
          <div class="form-row">
            <div class="form-item">
              <label>入库单号</label>
              <input v-model="editDialog.form.grnCode" type="text" readonly />
            </div>
            <div class="form-item">
              <label>采购单号</label>
              <input v-model="editDialog.form.poId" type="text" placeholder="请输入采购单号" />
            </div>
            <div class="form-item">
              <label>入库仓库</label>
              <select v-model="editDialog.form.warehouseId">
                <option value="">请选择仓库</option>
                <option v-for="item in warehouses" :key="item.id" :value="item.id">{{ item.whName }}</option>
              </select>
            </div>
          </div>

          <div class="divider">
            <span>入库商品</span>
          </div>
        
          <div class="items-container">
            <table class="data-table">
              <thead>
                <tr>
                  <th>商品名称</th>
                  <th>数量</th>
                  <th>单价</th>
                  <th>备注</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in editDialog.form.items" :key="index">
                  <td>
                    <select v-model="item.skuId" @change="() => handleEditProductSelect(item.skuId, index)">
                      <option value="">请选择商品</option>
                      <option v-for="prod in products" :key="prod.id" :value="prod.id">{{ prod.productName }}</option>
                    </select>
                  </td>
                  <td>
                    <input type="number" v-model="item.quantity" min="1" placeholder="数量" />
                  </td>
                  <td>
                    <input type="number" v-model="item.unitPrice" step="0.01" min="0" placeholder="单价" />
                  </td>
                  <td>
                    <input type="text" v-model="item.remark" placeholder="备注" />
                  </td>
                  <td>
                    <button v-if="index === 0" class="btn btn-small btn-success" @click="addEditItemRow">添加</button>
                    <button v-else class="btn btn-small btn-danger" @click="removeEditItemRow(index)">删除</button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="editDialog.visible = false">取消</button>
          <button class="btn btn-primary" @click="submitEdit" :disabled="editDialog.loading">保存修改</button>
        </div>
      </div>
    </div>

    <!-- 审核对话框 -->
    <div v-if="auditDialog.visible" class="modal-overlay" @click="auditDialog.visible = false">
      <div class="modal-content audit-modal" @click.stop>
        <div class="modal-header">
          <h3>入库单审核 - {{ auditDialog.data.grn?.grnCode }}</h3>
          <button class="modal-close" @click="auditDialog.visible = false">&times;</button>
        </div>
        <div class="modal-body">
          <!-- 入库单基本信息 -->
          <div class="audit-summary">
            <div class="summary-row">
              <div class="summary-item">
                <span class="label">入库单号：</span>
                <span>{{ auditDialog.data.grn?.grnCode }}</span>
              </div>
              <div class="summary-item">
                <span class="label">采购单号：</span>
                <span>{{ auditDialog.data.grn?.poId || '-' }}</span>
              </div>
              <div class="summary-item">
                <span class="label">仓库：</span>
                <span>{{ getWarehouseName(auditDialog.data.grn?.warehouseId) }}</span>
              </div>
            </div>
            <div class="summary-row">
              <div class="summary-item">
                <span class="label">供应商：</span>
                <span>{{ auditDialog.data.grn?.supplierId || '-' }}</span>
              </div>
              <div class="summary-item">
                <span class="label">入库类型：</span>
                <span>{{ auditDialog.data.grn?.inboundType || '-' }}</span>
              </div>
              <div class="summary-item">
                <span class="label">创建时间：</span>
                <span>{{ formatDate(auditDialog.data.grn?.createdAt) }}</span>
              </div>
            </div>
          </div>

          <!-- 入库明细 -->
          <div class="audit-details">
            <h4>入库明细</h4>
            <table class="data-table">
              <thead>
                <tr>
                  <th>商品名称</th>
                  <th>商品编码</th>
                  <th>批次号</th>
                  <th>库位</th>
                  <th>入库数量</th>
                  <th>单价</th>
                  <th>总价</th>
                  <th>备注</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in auditDialog.data.items || []" :key="index">
                  <td>{{ getProductName(item.skuId) }}</td>
                  <td>{{ getSkuCode(item.skuId) }}</td>
                  <td>{{ item.batchNo || '-' }}</td>
                  <td>{{ getLocationName(item.locationId) }}</td>
                  <td>{{ item.qty }}</td>
                  <td>{{ formatCurrency(item.unitPrice) }}</td>
                  <td>{{ formatCurrency((item.qty || 0) * (item.unitPrice || 0)) }}</td>
                  <td>{{ item.remark || '-' }}</td>
                </tr>
              </tbody>
            </table>
          </div>

          <!-- 审核意见 -->
          <div class="audit-opinion">
            <h4>审核意见</h4>
            <textarea v-model="auditDialog.opinion" placeholder="请输入审核意见..." rows="3"></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="auditDialog.visible = false">关闭</button>
          <button class="btn btn-danger" @click="handleAuditReject">审核驳回</button>
          <button class="btn btn-success" @click="handleAuditApprove">审核通过</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { apiGet, apiPost, apiPut, apiDelete } from '../../utils/api.js'

// 响应式数据
const searchForm = reactive({
  grnCode: '',
  warehouseId: '',
  status: ''
})

const grnList = ref([])
const warehouses = ref([])
const products = ref([])
const selectAll = ref(false)
const jumpPage = ref(1)

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 详情对话框
const detailDialog = reactive({
  visible: false,
  loading: false,
  data: {}
})

// 详情选项卡
const detailActiveTab = ref('items')
const operationHistory = ref([])

// 创建对话框
const createDialog = reactive({
  visible: false,
  loading: false,
  form: {
    grnCode: '',
    poId: '',
    warehouseId: '',
    items: [{ skuId: '', quantity: 1, unitPrice: 0, remark: '' }]
  }
})

// 审核对话框
const auditDialog = reactive({
  visible: false,
  loading: false,
  data: {},
  opinion: '',
  currentItem: null
})

// 编辑对话框
const editDialog = reactive({
  visible: false,
  loading: false,
  data: {},
  form: {
    grnCode: '',
    poId: '',
    warehouseId: '',
    items: [{ skuId: '', quantity: 1, unitPrice: 0, remark: '' }]
  }
})

// 修改状态跟踪
const modifiedItems = ref(new Set())

// 计算可见页码
const visiblePages = computed(() => {
  const currentPage = pagination.current
  const totalPages = Math.ceil(pagination.total / pagination.size)
  
  if (totalPages <= 5) {
    return Array.from({ length: totalPages }, (_, i) => i + 1)
  }
  
  if (currentPage <= 3) {
    return [1, 2, 3, 4, 5]
  }
  
  if (currentPage >= totalPages - 2) {
    return [totalPages - 4, totalPages - 3, totalPages - 2, totalPages - 1, totalPages]
  }
  
  return [currentPage - 2, currentPage - 1, currentPage, currentPage + 1, currentPage + 2]
})

// 获取入库单列表
const fetchGrnList = async () => {
  try {
    const params = new URLSearchParams({
        page: pagination.current,
        size: pagination.size,
      ...(searchForm.grnCode && { grnCode: searchForm.grnCode }),
      ...(searchForm.warehouseId && { warehouseId: searchForm.warehouseId }),
      ...(searchForm.status !== '' && { status: searchForm.status })
    })

    const data = await apiGet(`/ware-service/ware/grn/list?${params}`)
    
    if (data.records) {
      grnList.value = data.records.map(item => ({
        ...item,
        selected: false
      }))
      pagination.total = data.total || 0
      pagination.current = data.current || 1
    } else {
      grnList.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取入库单列表失败:', error)
    grnList.value = []
    pagination.total = 0
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.grnCode = ''
  searchForm.warehouseId = ''
  searchForm.status = ''
  pagination.current = 1
  fetchGrnList()
}

// 页码切换
const changePage = (page) => {
  if (page < 1 || page > Math.ceil(pagination.total / pagination.size)) return
  pagination.current = page
  fetchGrnList()
}

// 页码跳转
const jumpToPage = () => {
  const page = Number(jumpPage.value)
  if (page && page >= 1 && page <= Math.ceil(pagination.total / pagination.size)) {
    pagination.current = page
    fetchGrnList()
  }
}

// 全选/取消全选
const toggleSelectAll = () => {
  grnList.value.forEach(item => {
    item.selected = selectAll.value
  })
}

// 获取仓库名称
const getWarehouseName = (id) => {
  if (!id) return '-'
  const warehouse = warehouses.value.find(w => w.id === id)
  return warehouse ? warehouse.whName : '-'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '草稿',
    1: '待审核',
    2: '已审核',
    3: '已入库',
    4: '已驳回'
  }
  return statusMap[status] || '未知'
}

// 获取状态类名
const getStatusClass = (status) => {
  const classMap = {
    0: 'status-info',
    1: 'status-warning',
    2: 'status-success',
    3: 'status-primary',
    4: 'status-danger'
  }
  return `status ${classMap[status] || ''}`
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString()
}

// 格式化货币
const formatCurrency = (value) => {
  if (value === undefined || value === null) return '-'
  return `¥${parseFloat(value).toFixed(2)}`
}

// 查看入库单详情
const handleView = async (row) => {
  detailDialog.visible = true
  detailDialog.loading = true
  detailDialog.data = {}
  detailActiveTab.value = 'items'
  
  try {
    const result = await apiGet(`/ware-service/ware/grn/${row.id}`)
    detailDialog.data = result || {}
    
    // 模拟操作历史数据
    operationHistory.value = [
      {
        operateTime: detailDialog.data.grn?.createdAt,
        operationType: '创建入库单',
        operator: '系统',
        statusChange: '草稿',
        remark: '入库单创建'
      }
    ]
    
    // 根据状态添加历史记录
    if (detailDialog.data.grn?.status >= 1) {
      operationHistory.value.push({
        operateTime: detailDialog.data.grn?.createdAt,
        operationType: '提交审核',
        operator: '操作员',
        statusChange: '草稿 → 待审核',
        remark: '提交审核'
      })
    }
    
    if (detailDialog.data.grn?.status >= 2) {
      operationHistory.value.push({
        operateTime: detailDialog.data.grn?.createdAt,
        operationType: '审核通过',
        operator: '审核员',
        statusChange: '待审核 → 已审核',
        remark: '审核通过'
      })
    }
    
    if (detailDialog.data.grn?.status >= 3) {
      operationHistory.value.push({
        operateTime: detailDialog.data.grn?.receivedAt,
        operationType: '执行入库',
        operator: '仓管员',
        statusChange: '已审核 → 已入库',
        remark: '执行入库操作，库存已更新'
      })
    }
  } catch (error) {
    console.error('获取入库单详情失败:', error)
  } finally {
    detailDialog.loading = false
  }
}

// 新建入库单
const handleCreate = () => {
  createDialog.visible = true
  createDialog.form = {
    grnCode: `GRN${new Date().getTime()}`, // 生成默认编号
    poId: '',
    warehouseId: '',
    items: [{ skuId: '', quantity: 1, unitPrice: 0, remark: '' }]
  }
}

// 打开审核对话框
const handleApprove = async (item) => {
  auditDialog.visible = true
  auditDialog.loading = true
  auditDialog.data = {}
  auditDialog.opinion = ''
  auditDialog.currentItem = item
  
  try {
    const result = await apiGet(`/ware-service/ware/grn/${item.id}`)
    auditDialog.data = result || {}
  } catch (error) {
    console.error('获取入库单详情失败:', error)
  } finally {
    auditDialog.loading = false
  }
}

// 审核通过
const handleAuditApprove = async () => {
  try {
    const id = auditDialog.data.grn?.id
    
    const result = await apiPost(`/ware-service/ware/grn/${id}/approve`)
    if (result && (result.code === 0 || result.status === 200 || result.success)) {
      alert('入库单审核通过成功')
      auditDialog.visible = false
      await fetchGrnList()
    } else {
      alert('入库单审核失败')
    }
  } catch (error) {
    console.error('审核入库单失败:', error)
    alert('审核入库单失败')
  }
}

// 审核驳回
const handleAuditReject = async () => {
  if (!auditDialog.opinion.trim()) {
    alert('请输入驳回意见')
    return
  }
  
  try {
    const id = auditDialog.data.grn?.id
    const result = await apiPost(`/ware-service/ware/grn/${id}/reject`, {
      opinion: auditDialog.opinion
    })
    
    if (result && (result.code === 0 || result.status === 200 || result.success)) {
      alert('入库单已驳回')
      auditDialog.visible = false
      await fetchGrnList()
    } else {
      alert('驳回失败')
    }
  } catch (error) {
    console.error('驳回失败:', error)
    alert('驳回失败')
  }
}

// 打开编辑对话框
const handleEdit = async (item) => {
  editDialog.visible = true
  editDialog.loading = true
  editDialog.data = {}
  
  try {
    const result = await apiGet(`/ware-service/ware/grn/${item.id}`)
    editDialog.data = result || {}
    
    // 填充编辑表单
    if (editDialog.data.grn) {
      editDialog.form.grnCode = editDialog.data.grn.grnCode || ''
      editDialog.form.poId = editDialog.data.grn.poId || ''
      editDialog.form.warehouseId = editDialog.data.grn.warehouseId || ''
    }
    
    // 填充商品明细
    if (editDialog.data.items && editDialog.data.items.length > 0) {
      editDialog.form.items = editDialog.data.items.map(item => ({
        skuId: item.skuId || '',
        quantity: item.qty || 1,
        unitPrice: item.unitPrice || 0,
        remark: item.remark || ''
      }))
    } else {
      editDialog.form.items = [{ skuId: '', quantity: 1, unitPrice: 0, remark: '' }]
    }
  } catch (error) {
    console.error('获取入库单详情失败:', error)
  } finally {
    editDialog.loading = false
  }
}

// 编辑商品选择处理
const handleEditProductSelect = (skuId, index) => {
  if (skuId) {
    const product = products.value.find(p => p.id === skuId)
    if (product) {
      editDialog.form.items[index].unitPrice = product.unitPrice || 0
    }
  }
}

// 添加编辑商品行
const addEditItemRow = () => {
  editDialog.form.items.push({ skuId: '', quantity: 1, unitPrice: 0, remark: '' })
}

// 删除编辑商品行
const removeEditItemRow = (index) => {
  if (editDialog.form.items.length > 1) {
    editDialog.form.items.splice(index, 1)
  }
}

// 提交编辑
const submitEdit = async () => {
  if (!editDialog.form.warehouseId) {
    alert('请选择入库仓库')
    return
  }
  
  if (!editDialog.form.items.some(item => item.skuId)) {
    alert('请至少添加一个商品')
    return
  }
  
  editDialog.loading = true
  
  try {
    const id = editDialog.data.grn?.id
    const result = await apiPut(`/ware-service/ware/grn/${id}`, {
      grnCode: editDialog.form.grnCode,
      poId: editDialog.form.poId,
      warehouseId: editDialog.form.warehouseId,
      items: editDialog.form.items.map(item => ({
        skuId: item.skuId,
        qty: item.quantity,
        price: item.unitPrice
      }))
    })
    
    if (result && (result.code === 0 || result.status === 200 || result.success)) {
      alert('入库单修改成功')
      // 标记该单据为已修改
      modifiedItems.value.add(id)
      editDialog.visible = false
      await fetchGrnList()
    } else {
      alert('修改失败')
    }
  } catch (error) {
    console.error('修改入库单失败:', error)
    alert('修改失败')
  } finally {
    editDialog.loading = false
  }
}

// 执行入库
const handleExecute = async (id) => {
  if (confirm('确定要执行入库操作吗？')) {
    try {
      const result = await apiPost(`/ware-service/ware/grn/${id}/execute`)
      if (result && (result.code === 0 || result.status === 200 || result.success)) {
        alert('入库操作成功')
        await fetchGrnList()
      } else {
        alert('入库操作失败')
      }
    } catch (error) {
      console.error('执行入库失败:', error)
      alert('执行入库失败')
    }
  }
}

// 删除入库单
const handleDelete = async (id) => {
  if (confirm('确定要删除此入库单吗？')) {
    try {
      const result = await apiDelete(`/ware-service/ware/grn/${id}`)
      if (result && (result.code === 0 || result.status === 200 || result.status === 204 || result.success)) {
        alert('入库单删除成功')
        await fetchGrnList()
      } else {
        alert('入库单删除失败')
      }
    } catch (error) {
      console.error('删除入库单失败:', error)
      alert('删除入库单失败')
    }
  }
}

// 提交审核
const handleSubmit = async (id) => {
  // 检查是否是驳回状态的单据
  const item = grnList.value.find(item => item.id === id)
  if (item && item.status === 4) {
    // 如果是驳回状态，检查是否已修改
    if (!modifiedItems.value.has(id)) {
      alert('已驳回的单据必须先进行修改才能提交审核，请先点击"编辑"按钮修改单据内容')
      return
    }
  }
  
  if (confirm('确定要提交此入库单进行审核吗？')) {
    try {
      const result = await apiPost(`/ware-service/ware/grn/${id}/submit`)
      if (result && (result.code === 0 || result.status === 200 || result.success)) {
        alert('入库单提交审核成功')
        // 提交成功后，移除修改标记
        modifiedItems.value.delete(id)
        await fetchGrnList()
      } else {
        alert('入库单提交失败')
      }
    } catch (error) {
      console.error('提交入库单失败:', error)
      alert('提交入库单失败')
    }
  }
}

// 添加商品行
const addItemRow = () => {
  createDialog.form.items.push({ skuId: '', quantity: 1, unitPrice: 0, remark: '' })
}

// 删除商品行
const removeItemRow = (index) => {
  createDialog.form.items.splice(index, 1)
}

// 商品选择事件
const handleProductSelect = (value, index) => {
  const product = products.value.find(p => p.id === value)
  if (product && createDialog.form.items[index]) {
    createDialog.form.items[index].unitPrice = product.price || 0
  }
}

// 提交入库单
const submitGrn = async () => {
  // 表单验证
  if (!createDialog.form.grnCode) {
    alert('请输入入库单号')
    return
  }
  
  if (!createDialog.form.warehouseId) {
    alert('请选择入库仓库')
    return
  }
  
  if (createDialog.form.items.some(item => !item.skuId)) {
    alert('请选择所有商品')
    return
  }
    
  createDialog.loading = true
  
  try {
    // 转换字段名以匹配后端期望
    const submitData = {
      ...createDialog.form,
      items: createDialog.form.items.map(item => ({
        skuId: item.skuId || '',
        qty: item.quantity || 1,
        price: item.unitPrice || 0,
        remark: item.remark || ''
      })).filter(item => item.skuId && item.qty > 0) // 过滤无效数据
    }
    
    const result = await apiPost('/ware-service/ware/grn', submitData)
    if (result && (result.code === 0 || result.status === 200 || result.status === 201 || result.success)) {
      alert('入库单创建成功')
      createDialog.visible = false
      await fetchGrnList()
    } else {
      alert('入库单创建失败')
    }
  } catch (error) {
    console.error('创建入库单失败:', error)
    alert('创建入库单失败')
  } finally {
    createDialog.loading = false
  }
}

// 获取仓库列表
const fetchWarehouses = async () => {
  try {
    const params = new URLSearchParams({
      page: 1,
      size: 100
    })
    
    const data = await apiGet(`/ware-service/warehouse/list?${params}`)
    
    if (data.records) {
      warehouses.value = data.records || []
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    warehouses.value = []
  }
}

// 获取商品列表
const fetchProducts = async () => {
  try {
    const params = new URLSearchParams({
      page: 1,
      size: 100
    })
    
    const data = await apiGet(`/ware-service/ware/sku/list?${params}`)
    
    if (data.records) {
      products.value = data.records || []
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    products.value = []
  }
}

// 根据SKU ID获取商品名称
const getProductName = (skuId) => {
  const product = products.value.find(p => p.id === skuId)
  return product ? product.productName : '未知商品'
}

// 根据SKU ID获取SKU编码
const getSkuCode = (skuId) => {
  const product = products.value.find(p => p.id === skuId)
  return product ? product.skuCode : '-'
}

// 获取库位名称
const getLocationName = (locationId) => {
  if (!locationId) return '-'
  // 这里可以从库位列表中获取，暂时返回默认值
  return `库位-${locationId}`
}

// 计算总数量
const getTotalQuantity = () => {
  const items = detailDialog.data.items || []
  return items.reduce((total, item) => {
    return total + (item.qty || item.quantity || 0)
  }, 0)
}

// 计算总金额
const getTotalAmount = () => {
  const items = detailDialog.data.items || []
  return items.reduce((total, item) => {
    const qty = item.qty || item.quantity || 0
    const price = item.price || item.unitPrice || 0
    return total + (qty * price)
  }, 0)
}

// 生命周期
onMounted(() => {
  fetchGrnList()
  fetchWarehouses()
  fetchProducts()
})
</script>

<style scoped>
.order-payment {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #333;
}

.breadcrumb {
  color: #666;
  font-size: 14px;
}

.search-section {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 16px;
}

.form-item {
  display: flex;
  flex-direction: column;
  min-width: 200px;
}

.form-item label {
  font-size: 14px;
  margin-bottom: 5px;
  color: #333;
}

.form-item input,
.form-item select {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.form-buttons {
  display: flex;
  gap: 10px;
  align-items: flex-end;
  margin-top: 24px;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-start;
}

.table-container {
  margin-bottom: 20px;
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  border: 1px solid #ddd;
  padding: 10px;
  text-align: left;
}

.data-table th {
  background-color: #f8f9fa;
  font-weight: bold;
}

.data-table tr:nth-child(even) {
  background-color: #f9f9f9;
}

.text-center {
  text-align: center;
}

.status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-info {
  background-color: #e6f7ff;
  color: #1890ff;
}

.status-warning {
  background-color: #fff7e6;
  color: #fa8c16;
}

.status-success {
  background-color: #e6fffb;
  color: #13c2c2;
}

.status-primary {
  background-color: #f0f5ff;
  color: #2f54eb;
}

.status-danger {
  background-color: #fff2f0;
  color: #ff4d4f;
}

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.pagination-controls {
  display: flex;
  gap: 5px;
}

.pagination-jump {
  display: flex;
  align-items: center;
  gap: 5px;
}

.pagination-jump input {
  width: 50px;
  padding: 4px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.btn-primary {
  background-color: #1890ff;
  color: white;
}

.btn-secondary {
  background-color: #f5f5f5;
  color: #333;
}

.btn-success {
  background-color: #52c41a;
  color: white;
}

.btn-info {
  background-color: #1890ff;
  color: white;
}

.btn-danger {
  background-color: #ff4d4f;
  color: white;
}

.btn-small {
  padding: 4px 8px;
  font-size: 12px;
}

.btn-page {
  padding: 4px 10px;
  min-width: 30px;
  background-color: #fff;
  border: 1px solid #ddd;
}

.btn-page.active {
  background-color: #1890ff;
  color: white;
  border-color: #1890ff;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  width: 500px;
  max-width: 90%;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #ddd;
}

.modal-header h3 {
  margin: 0;
}

.modal-close {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
}

.modal-body {
  padding: 20px;
}

.modal-footer {
  padding: 16px 20px;
  border-top: 1px solid #ddd;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.divider {
  display: flex;
  align-items: center;
  margin: 20px 0;
}

.divider::before,
.divider::after {
  content: "";
  flex-grow: 1;
  height: 1px;
  background-color: #ddd;
}

.divider span {
  padding: 0 10px;
  color: #666;
  font-size: 14px;
}

.items-container {
  margin-top: 16px;
}

.detail-header {
  margin-bottom: 20px;
}

.detail-row {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
}

.detail-item {
  flex: 1;
  min-width: 250px;
  padding-right: 20px;
}

.detail-label {
  font-weight: bold;
  color: #666;
}

.detail-content {
  margin-top: 20px;
}

.detail-content h3 {
  margin-bottom: 10px;
  font-size: 16px;
  color: #333;
}

/* 详情选项卡样式 */
.detail-tabs {
  margin-top: 20px;
}

.tab-header {
  display: flex;
  border-bottom: 2px solid #f0f0f0;
  margin-bottom: 20px;
}

.tab-btn {
  padding: 12px 24px;
  border: none;
  background: none;
  cursor: pointer;
  font-size: 14px;
  color: #666;
  border-bottom: 2px solid transparent;
  transition: all 0.3s ease;
}

.tab-btn:hover {
  color: #1890ff;
}

.tab-btn.active {
  color: #1890ff;
  border-bottom-color: #1890ff;
  font-weight: 500;
}

.tab-content {
  min-height: 200px;
}

/* 汇总信息样式 */
.summary-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.summary-card {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.summary-card h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: #333;
  border-bottom: 1px solid #e9ecef;
  padding-bottom: 8px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding: 8px 0;
}

.stat-label {
  color: #666;
  font-size: 14px;
}

.stat-value {
  color: #333;
  font-size: 14px;
  font-weight: 500;
}

/* 审核对话框样式 */
.modal-content.audit-modal {
  width: 1200px;
  max-width: 95vw;
}

/* 审核详情样式 */
.audit-summary {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.summary-row {
  display: flex;
  gap: 30px;
  flex-wrap: wrap;
}

.summary-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.summary-item .label {
  font-weight: bold;
  color: #666;
}

/* 审核详情 */
.audit-details {
  margin-bottom: 20px;
}

.audit-details h4 {
  margin-bottom: 12px;
  color: #333;
}

/* 审核意见 */
.audit-opinion {
  margin-bottom: 20px;
}

.audit-opinion h4 {
  margin-bottom: 12px;
  color: #333;
}

.audit-opinion textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: vertical;
  font-family: inherit;
}
</style>


